// 创建自定义指令-----鼠标移动做拽
const vDraggable = {
  mounted(el: HTMLElement) {
    let isDragging = false;
    let offsetX = 0;
    let offsetY = 0;

    const handleMouseDown = (e: MouseEvent) => {
      isDragging = true;
      offsetX = e.clientX - el.offsetLeft;
      offsetY = e.clientY - el.offsetTop;
      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);
    };

    const handleMouseMove = (e: MouseEvent) => {
      if (!isDragging) return;
      // el.style.left = `${e.clientX - offsetX}px`;
      // el.style.top = `${e.clientY - offsetY}px`;
      const newLeft = e.clientX - offsetX;
      const newTop = e.clientY - offsetY;

      // 计算边界
      const maxLeft = window.innerWidth; // - el.offsetWidth
      const maxTop = window.innerHeight; // - el.offsetHeight

      // 确保元素在边界内
      const left = Math.max(el.offsetWidth, Math.min(newLeft, maxLeft));
      const top = Math.max(el.offsetHeight, Math.min(newTop, maxTop));
      el.style.left = `${left}px`;
      el.style.top = `${top}px`;
    };

    const handleMouseUp = () => {
      isDragging = false;
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
    };

    el.addEventListener("mousedown", handleMouseDown);
  },
};

export default {
  install(app: any) {
    app.directive("draggable", vDraggable);
  },
};
